package com.xyrx.xyrxcamundademo.controller;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xyrx.xyrxcamundademo.camunda.PscCommonProcessRequest;
import javafx.scene.control.Tab;
import org.apache.commons.lang3.StringUtils;
import org.camunda.bpm.engine.*;
import org.camunda.bpm.engine.rest.dto.task.TaskDto;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author JsDeng
 * @date 2020/5/28
 */
@Service
public class SimpleProcessHandlerImpl implements SimpleProcessHandler{
    private static final Logger logger = LoggerFactory.getLogger(SimpleProcessHandlerImpl.class);

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private TaskService taskService;

    @Override
    public List<TaskDto> simpleInitProcess(HttpServletRequest request) throws Exception {
        PscCommonProcessRequest pscCommonProcessRequest = JSONUtil.toBean(request.getParameter("pscCommonProcessRequest"), PscCommonProcessRequest.class);
        System.out.println(pscCommonProcessRequest.toString());
        String processInstanceId = null;
        List<TaskDto> resultList = new ArrayList<TaskDto>();
        Map<String, Object> variables = new HashMap<String, Object>();
        variables = pscCommonProcessRequest.getVariables();
        // variables.put("assigneeList030", Arrays.asList("kermit", "demo"));
        // variables.put("assigneeList040", Arrays.asList("kermit", "demo"));
//        variables.put("starter", pscCommonProcessRequest.getStarter());
        variables.put("amount", "980");
        // 流程初始化
        ProcessInstance processInstance = null;
        // 流程初始化
        if (StringUtils.isNotBlank(pscCommonProcessRequest.getProcessDefKey())) {
            processInstance = runtimeService.startProcessInstanceByKey(pscCommonProcessRequest.getProcessDefKey(),
                    variables);
        } else {
            processInstance = runtimeService.startProcessInstanceById(pscCommonProcessRequest.getProcessDefId(),
                    variables);
        }
        // 创建成功
        if (processInstance != null && StringUtils.isNotBlank(processInstance.getId())) {
            processInstanceId = processInstance.getId();
            resultList = simpleGetTasks(processInstanceId);
        } else {
            throw new Exception("创建流程实例失败：");
        }
        return resultList;
    }

    public List<TaskDto> simpleGetTasks(String processInstId) throws Exception {
        List<TaskDto> resultList = new ArrayList<TaskDto>();
        List<Task> taskList = taskService.createTaskQuery().processInstanceId(processInstId).list();
        for (Task task : taskList) {
            TaskDto dto = new TaskDto();
            dto = TaskDto.fromEntity(task);
            resultList.add(dto);
        }
        return resultList;
    }

    @Override
    public String simpleGetProcessDiagramUrl(String processInstId, String uid, HttpServletRequest request) throws Exception {
        InputStream processDiagram = repositoryService.getProcessDiagram("");
        // 输出图片内容
        byte[] b = new byte[1024];
        int len;
        while ((len = processDiagram.read(b, 0, 1024)) != -1) {
//            processDiagram.write(b, 0, len);
        }

        return null;
    }
}
